package com.cuixichang.minimalism.core.security.filter;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.cuixichang.minimalism.basal.cnstants.HttpHeader;
import com.cuixichang.minimalism.core.security.design.JWTAnalysisDesign;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

public class JwtSecurityAuthenticationFilter extends GenericFilterBean {
    private static final Log logfactory = LogFactory.get();

    public JwtSecurityAuthenticationFilter(JWTAnalysisDesign jwtAnalysisDesign) {
        this.jwtAnalysisDesign = jwtAnalysisDesign;
    }

    private JWTAnalysisDesign jwtAnalysisDesign;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authorization = request.getHeader(HttpHeader.AUTHORIZATION);
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if(Objects.isNull(authentication) || !authentication.isAuthenticated()){
                if(StringUtils.hasText(authorization)) {
                    if(logfactory.isDebugEnabled()){
                        logfactory.debug("{0} {1}",HttpHeader.AUTHORIZATION,authorization);
                    }
                    Authentication reverse = jwtAnalysisDesign.reverse(authorization);
                    if(Objects.nonNull(reverse)){
                        SecurityContextHolder.getContext().setAuthentication(reverse);
                    }
                }
            }
        }catch (Exception e){
            if(logfactory.isDebugEnabled()){
                logfactory.debug(e);
            }
        } finally {
            filterChain.doFilter(request, servletResponse);
        }
    }
}
